#include <sys/stat.h>
#include "Directory.h"
#include "vector"
#include "cstring"
namespace zg_util{

    bool Directory::IsExists(std::string path) {
        struct stat st;
        return stat(path.c_str(),&st)==0;
    }
    /*非线程安全*/
    bool Directory::CreateDirectory(std::string dir,bool ischdir) {
        char cur_dir[1024]={0};
        char tmp[1024];
        char *p;
        if (dir.size() == 0) {
            return false;
        }
        if(!ischdir){
            getcwd(cur_dir,1024);
        }
        memset(tmp, '\0', sizeof(tmp));
        strncpy(tmp, dir.data(), dir.size());
        if (tmp[0] == '/')
            p = strchr(tmp + 1, '/');
        else
            p = strchr(tmp, '/');
        if (p) {
            *p = '\0';

            if(!IsExists(tmp)){
             if(mkdir(tmp, S_IRWXU))
                return false;
            }
            chdir(tmp);
        } else {

            if(!IsExists(tmp)) {
                if (mkdir(tmp, S_IRWXU))
                    return false;
            }
            chdir(tmp);
            return true;
        }
        if(!CreateDirectory(std::string(p + 1),true)){
            return false;
        }
        if(!ischdir){
            chdir(cur_dir);
        }
        return  true;
    }
}